(function($) {
  $.widget("webtool.textareaResize", {
    _create: function() {
      var iLastMousePos = 0;
      var textarea;
      var staticOffset;
      var iMin = 64;
      var mousePosition = function (e) {
        return {
          x: e.clientX + document.documentElement.scrollLeft,
          y: e.clientY + document.documentElement.scrollTop
        }
      }
      var performDrag = function (e) {
        var iThisMousePos = mousePosition(e).y;
        var iMousePos = staticOffset + iThisMousePos;
        if (iLastMousePos >= (iThisMousePos)) {
          iMousePos -= 5
        }
        iLastMousePos = iThisMousePos;
        iMousePos = Math.max(iMin, iMousePos);
        textarea.height(iMousePos + 'px');
        if (iMousePos < iMin) {
          endDrag(e)
        }
        return false
      }
      var endDrag = function (e) {
        $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
        textarea.css('opacity', 1);
        textarea.focus();
        textarea = null;
        staticOffset = null;
        iLastMousePos = 0
      }
      var startDrag = function(e){
        textarea = e.data.el;
        textarea.blur();
        iLastMousePos = mousePosition(e).y;
        staticOffset = textarea.height() - iLastMousePos;
        textarea.css('opacity', 0.5);
        $(document).mousemove(performDrag).mouseup(endDrag);
        return false
      }
      var gripClick = function(e) {
    	  textarea = e.data.el;
    	  if (textarea[0].scrollHeight > textarea[0].offsetHeight) {
    		  textarea.height(textarea[0].scrollHeight);
    		  textarea[0].scrollHeight = 0;
    	  }    	  
      }
      this.element.each(function(){
        var that = $(this);
        that.css("resize", "none").wrap('<div class="resizable-textarea"><span></span></div>');
        var grippie = $("<div/>", {class: "grippie", style: "resize: none;"}).appendTo(that.parent());
        $("<i/>", {class: "fa fa-angle-double-down"}).appendTo(grippie);
        grippie.bind("mousedown", {el:that}, startDrag);
        grippie.bind("dblclick",{el:that}, gripClick);
        // TODO 移动端兼容
        // TODO 有滚动条时，双击自动伸展至滚动条消失
      })
    }

  });
})(jQuery);
